﻿using MailKit.Net.Smtp;
using MimeKit;
using MailKit;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using System;

namespace Enter.Admin.Utils
{
    public class MailModel
    {
        public bool Enable { get; set; }
        public string Host { get; set; } = string.Empty;
        public int Port { get; set; }
        public string UserName { get; set; } = string.Empty;
        public string Password { get; set; } = string.Empty;
        public string FromAddress { get; set; } = string.Empty;
        public string FromName { get; set; } = string.Empty;
        public string ToAddress { get; set; } = string.Empty;
        public string ToName { get; set; } = string.Empty;

        public void Send(string subject, string body) 
        {
            if (!this.Enable) return;
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(this.FromName, this.FromAddress));
            message.To.Add(new MailboxAddress(this.ToName, this.ToAddress));
            message.Subject = subject;
            message.Body = new TextPart("html") // new TextPart("plain") //new TextPart("html")
            {
                Text = body
            };
            using (var client = new SmtpClient())
            {
                client.Connect(this.Host, this.Port, false);
                client.Authenticate(this.UserName, this.Password);
                client.Send(message);
                client.Disconnect(true);
            }
        }
    }

    // https://github.com/jstedfast/MailKit
    // https://github.com/lukencode/FluentEmail
    public class Mail
    {
        private readonly ILogger<Mail> _logger;
        private readonly MailModel _setting;
		private string _toName = string.Empty;
		private string _toAddress = string.Empty;
        public Mail(ILogger<Mail> logger, IOptionsSnapshot<MailModel> setting)
        {
            // Configuration.GetSection("Mail").Get<MailModel>();
            _logger = logger;
            _setting = setting.Value;
        }
        /*
            IOptions<T> //站点启动后，获取到的值永远不变 
            IOptionsSnapshot<T> //站点启动后，每次获取到的值都是配置文件里的最新值 （reloadOnChange:true 必须为true）        
            IOptionsMonitor<T> //站点启动后，如果配置文件有变化会发布事件 （reloadOnChange:true 必须为true）
        */
        public void SetTo(string toName, string toAddress)
        {
			_toName = toName;
			_toAddress = toAddress;
        }
       
        public bool Send(string subject, string body)
        {
            if (!string.IsNullOrWhiteSpace(_toName)) 
            {
                _setting.ToName = _toName;
            }
            if (!string.IsNullOrWhiteSpace(_toAddress))
            {
                _setting.ToAddress = _toAddress;
            }
           
            try
            {
                _setting.Send(subject, body);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送邮件异常: {0}", ex.Message);
                return false;
            }
        }
    }    
}
